<?php
/**
 * Introduction: 商品逻辑处理
 * @author: 杨陈鹏
 * @date: 2016/4/13 16:08
 * @email: yangchenpeng@cdlinglu.com
 */

namespace Common\Logic;

use Common\Model;

class GoodsLogic
{

    static public $model, $extend, $goods_collection;

    public function __construct()
    {

        self::$model = new Model\GoodsModel();

        self::$extend = new Model\GoodsExtendModel();

        self::$goods_collection = new Model\GoodsCollectionModel();

    }

    /**
     * Introduction: 获取商品，不带默认数据
     * @author: 杨陈鹏
     * @date: 2016/4/13 16:08
     * @email: yangchenpeng@cdlinglu.com
     * @param: $where array or string 查询条件
     * @param: $page int 分页页码
     * @param: $fields string 需要查询的主表字段
     * @param: $order int 排序规则   1:按人气排序 2:按销量排序  3:按发布时间排序
     *
     */

    static public function datas($where = '', $limit = '0,20', $fields = '*', $order = 'create_time desc')
    {


        $data = self::$model
            ->where($where)
            ->order($order)
            ->limit($limit)
            ->field($fields)
            ->select();

        if ($data)
            return ['code' => 200, 'data' => $data];

        return ['code' => 300, 'msg' => '暂无数据!'];

    }

    /**
     * Introduction: 获取商品列表
     * @author: 杨陈鹏
     * @date: 2016/4/13 16:08
     * @email: yangchenpeng@cdlinglu.com
     * @param: $where array or string 查询条件
     * @param: $page int 分页页码
     * @param: $fields string 需要查询的主表字段
     * @param: $order int 排序规则   1:按人气排序 2:按销量排序  3:按发布时间排序
     *
     */
    static public function getData($where = [], $page = 1, $fields = '*', $orders = ['column' => 'add_time', 'type' => 'desc'], $nums = 20)
    {

        //每页显示数量


        $order = $orders['column'] ? $orders['column'] : 'add_time';

        $order .= $orders['type'] ? ' ' . $orders['type'] : ' desc';

        $data = self::$model
            //->fetchSql(true)
            ->relation('goods_extend')
            ->where($where)
            ->page($page, $nums)
            ->order($order)
            ->field($fields)
            ->select();

        $total = self::$model->where($where)->count();

        if (!$data)
            return ['code' => 200, 'msg' => '暂无数据', 'data' => []];


        foreach ($data as $k => $v) {

            $data[$k]['storage_total'] = self::getStorageTotal($v['id']);
            $data[$k]['product_data'] = unserialize($v['product_data']);
            $data[$k]['add_time'] = date('Y-m-d H:i:s',$data[$k]['add_time']);
            $data[$k]['spec'] = unserialize($v['spec']);
            $data[$k]['goods_extend']['slide'] = unserialize($v['goods_extend']['slide']);

        }

        return ['code' => 200, 'data' => $data, 'total' => $total];


    }

    /**
     * Introduction: 获取单个商品(不带附表数据)
     * @author: 杨陈鹏
     * @date: 2016/4/13 16:08
     * @email: yangchenpeng@cdlinglu.com
     * @param: $where array or string 查询条件
     * @param: $fields string 需要查询的主表字段
     *
     */
    static public function getOneData($where = [], $fields = '*')
    {

        self::$model->where($where)->setInc('views',1);

        $data = self::$model
            ->relation('goods_extend')
            ->where($where)
            ->field($fields)
            ->find();

        if (!$data)
            return ['code' => 200, 'msg' => '暂无数据', 'data' => []];


        $data['storage_total'] = self::getStorageTotal($data['id']);
        $data['product_data'] = unserialize($data['product_data']);
        $data['spec'] = unserialize($data['spec']);
        $data['goods_extend']['slide'] = unserialize($data['goods_extend']['slide']);

        //获取当前商品的顶级分类
        $top_category   =   self::getTopCategory($data['category_id']);
        $category_logic =   new CategoryLogic();
        //获取所有规则
        $categorys = $category_logic::getChilds($top_category, 'id');

        $category_ids   =   '';
        foreach( $categorys as $v ){
            $category_ids   .= $v['id'].',';
        }
        $category_ids   =   rtrim($category_ids,',');

        $related       =   self::$model
            ->where(["category_id IN($category_ids)"])
            ->order('goods_salenum desc,views desc,comment desc,share_nums desc')
            ->page(1,8)
            ->field('id,title,description,thumb,goods_price,is_distribution')
            ->select();

        if ( !$related )
            $related   = [];

        $data['related']       = $related;

        return ['code' => 200, 'data' => $data];


    }

    static public function getTopCategory($category_id)
    {

        $category_logic     =   new CategoryLogic();

        $category_parent    =   $category_logic::$model
            ->where(['id' => $category_id])
            ->getField('pid');
        if ( !$category_parent )
        {
            $c_id =  $category_id;
        } else {
           $c_id  = self::getTopCategory($category_parent);
        }
        return $c_id;


    }

    /**
     * Introduction: 获取单个商品(带附表数据)
     * @author: 杨陈鹏
     * @date: 2016/4/13 16:08
     * @email: yangchenpeng@cdlinglu.com
     * @param: $where array or string 查询条件
     * @param: $fields string 需要查询的主表字段
     *
     */
    static public function getOneDatas($goods_id)
    {

        $data = self::$model
            ->where(['id' => $goods_id])
            ->find();

        if (!$data)
            return ['code' => 200, 'msg' => '暂无数据', 'data' => []];


        $data['storage_total'] = self::getStorageTotal($data['id']);
        $data['product_data'] = unserialize($data['product_data']);
        $data['spec'] = unserialize($data['spec']);
        $data['goods_extend']['slide'] = unserialize($data['goods_extend']['slide']);

        $data['goods_extend'] = self::$extend
                                            ->where(['goods_id' => $goods_id])
                                            ->select();

        foreach ( $data['goods_extend'] as $k => $v)
        {

            $data['goods_extend'][$k]['slide'] = unserialize($data['goods_extend'][$k]['slide']);

        }

        return ['code' => 200, 'data' => $data];


    }

    /**
     * Introduction: 获取商品规格
     * @author: 杨陈鹏
     * @date: 2016/4/13 16:08
     * @email: yangchenpeng@cdlinglu.com
     * @param: $where array or string 查询条件
     *
     */
    static public function getSpec($where, $fields = '*')
    {

        $data = self::$extend
            ->where($where)
            ->field($fields)
            ->find();

        if (!$data)
            return ['code' => 300, 'msg' => '此商品缺货!'];


        $data['slide'] = unserialize($data['slide']);

        return ['code' => 200, 'data' => $data];


    }

    /**
     * Introduction: 获取商品总库存
     * @author: 杨陈鹏
     * @date: 2016/4/13 16:08
     * @email: yangchenpeng@cdlinglu.com
     * @param: $goods_id int 商品ID
     */

    static public function getStorageTotal($goods_id)
    {

        if (!intval($goods_id))
            return false;

        return self::$extend
            ->where(['goods_id' => $goods_id])
            ->sum('goods_storage');


    }

    /**
     * Introduction: 发布商品
     * @author: 杨陈鹏
     * @date: 2016/4/13 16:08
     * @email: yangchenpeng@cdlinglu.com
     * @param: $data array 商品数据
     */
    static public function create($data)
    {

        if (!$data || !$data['basic'] || !$data['extend'])
            return ['code' => 300, 'msg' => '参数错误'];

        //组装商品主表信息

        if (!$data['basic']['title'])
            return ['code' => 300, 'msg' => '商品标题不能为空'];

        if (!$data['basic']['category_id'])
            return ['code' => 300, 'msg' => '商品分类不能为空'];

        $master['title']            = $data['basic']['title'];
        //$master['keywords'] = $data['basic']['keywords'];
        $master['description']      = $data['basic']['description'] ? $data['basic']['description'] : '' ;
        $master['content']          = $data['basic']['content'] ? $data['basic']['content'] : '' ;
        $master['category_id']      = $data['basic']['category_id'];
        $master['add_time']         = NOW_TIME;
        $master['update_time']      = NOW_TIME;
        $master['transport_id']     = $data['basic']['transport_id'] ? $data['basic']['transport_id'] : 0 ;
        $master['goods_freight']    = $data['basic']['goods_freight'] ? $data['basic']['goods_freight'] * 100 : 0 ;
        $master['thumb']            = $data['basic']['thumb'] ? $data['basic']['thumb'] : '' ;
        $master['is_own_shop']      = 1;
        $master['product_data']     = $data['basic']['product_data'] ? serialize($data['basic']['product_data']) : serialize([]);
        $master['is_distribution']  = $data['basic']['is_distribution'];
        $master['bonus']            = $data['basic']['bonus'];



        foreach ($data['basic']['spec'] as $k => $v) {

            $data['basic']['spec'][$k]['attr_val'] = unique($data['basic']['spec'][$k]['attr_val']);

        }

        $master['publish_time']         = $data['basic']['publish_time'] ? strtotime($data['basic']['publish_time']) : NOW_TIME;
        $master['spec']                 = $data['basic']['spec'] ? serialize($data['basic']['spec']) : serialize([]);
        $master['goods_state']          = $data['basic']['goods_state'] ? $data['basic']['goods_state'] : 0;
        $master['goods_price']          = intval($data['basic']['goods_price']) * 100;
        $master['goods_market_price']   = intval($data['basic']['goods_market_price']) * 100;

        //return $master;
        //开启事物
        self::$extend->startTrans();

        if (!$id = self::$model->add($master))
            return ['code' => 300, 'msg' => '发布失败'];

        $result = [];

        foreach ($data['extend'] as $v) {

            $v['goods_id']              = $id;
            $v['slide']                 = serialize($v['slide']);

            $v['goods_price']           = intval($v['goods_price']) * 100;
            $v['goods_promotion_price'] = intval($v['goods_promotion_price']) * 100;
            $v['goods_market_price']    = intval($v['goods_market_price']) * 100;
            $v['goods_cost_price']      = intval($v['goods_cost_price']) * 100;

            $result[] = self::$extend->add($v);

        }

        if (!is_array(false, $result)) {

            self::$extend->commit();

            return ['code' => 200, 'msg' => '保存成功'];

        } else {

            self::$model->where(['id' => $id])->delete();

            self::$extend->rollback();

            return ['code' => 300, 'msg' => '发布失败!', 'data' => $result];

        }


    }

    /**
     * Introduction: 修改商品
     * @author: 杨陈鹏
     * @date: 2016/4/13 16:08
     * @email: yangchenpeng@cdlinglu.com
     * @param: $data array 商品数据
     */
    static public function update($data,$goods_id)
    {

        if (!$data)
            return ['code' => 300, 'msg' => '数据不能为空'];

        if(!$data['basic'] )
            return ['code' => 300, 'msg' => '商品基础数据不能为空'];

        if( !$data['extend'] )
            return ['code' => 300, 'msg' => '商品默认不能为空'];

        if( !$goods_id)
            return ['code' => 300, 'msg' => '缺少商品ID'];

        //组装商品主表信息

        if (!$data['basic']['title'])
            return ['code' => 300, 'msg' => '商品标题不能为空'];

        if (!$data['basic']['category_id'])
            return ['code' => 300, 'msg' => '商品分类不能为空'];

        $master['title']            = $data['basic']['title'];
        //$master['keywords'] = $data['basic']['keywords'];
        $master['description']      = $data['basic']['description'] ? $data['basic']['description'] : '' ;
        $master['content']          = $data['basic']['content'] ? $data['basic']['content'] : '' ;
        $master['category_id']      = $data['basic']['category_id'];
        $master['update_time']      = NOW_TIME;
        $master['transport_id']     = $data['basic']['transport_id'] ? $data['basic']['transport_id'] : 0 ;
        $master['goods_freight']    = $data['basic']['goods_freight'] ? $data['basic']['goods_freight'] * 100 : 0 ;
        $master['thumb']            = $data['basic']['thumb'] ? $data['basic']['thumb'] : '' ;
        $master['is_own_shop']      = 1;
        $master['product_data']     = $data['basic']['product_data'] ? serialize($data['basic']['product_data']) : serialize([]);
        $master['publish_time']     = $data['basic']['publish_time'] ? strtotime($data['basic']['publish_time']) : NOW_TIME;
        $master['is_distribution']  = $data['basic']['is_distribution'];
        $master['bonus']            = $data['basic']['bonus'];


        foreach ($data['basic']['spec'] as $k => $v) {

            $data['basic']['spec'][$k]['attr_val'] = unique($data['basic']['spec'][$k]['attr_val']);

        }

        $master['spec']                 = $data['basic']['spec'] ? serialize($data['basic']['spec']) : serialize([]);
        $master['goods_state']          = $data['basic']['goods_state'] ? $data['basic']['goods_state'] : 0;
        $master['goods_price']          = intval($data['basic']['goods_price']) * 100;
        $master['goods_market_price']   = intval($data['basic']['goods_market_price']) * 100;

        self::$extend->where(['goods_id' => $goods_id])->setField('is_default',0);

        //开启事物
        self::$extend->startTrans();

        if (!self::$model->where(['id' => $goods_id])->save($master))
            return ['code' => 300, 'msg' => '更新失败'];

        $result = [];

        foreach ($data['extend'] as $v) {

            $v['goods_id']              = $goods_id;
            $v['slide']                 = serialize($v['slide']);

            $v['goods_price']           = intval($v['goods_price']) * 100;
            $v['goods_promotion_price'] = intval($v['goods_promotion_price']) * 100;
            $v['goods_market_price']    = intval($v['goods_market_price']) * 100;
            $v['goods_cost_price']      = intval($v['goods_cost_price']) * 100;

            if(intval($v['id'])){

                $id = $v['id'];

                unset($v['id']);

                $result[] = self::$extend->where(['id' => $id])->save($v);

            } else {

                $result[] = self::$extend->add($v);

            }

        }

        if (!is_array(false, $result)) {

            self::$extend->commit();

            return ['code' => 200, 'msg' => '更新成功'];

        } else {

            self::$extend->rollback();

            return ['code' => 300, 'msg' => '更新失败!', 'data' => $result];

        }


    }

    /**
     * @introduction: 计算商品运费
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     * @param array $data 商品数据
     */
    static public function freight($data)
    {

        if (!$data['goods_id'])
            return ['code' => 300, 'msg' => '缺少商品信息!'];

        if (!$data['county_id'])
            return ['code' => 300, 'msg' => '缺少县区信息!'];

        if (!$data['city_id'])
            return ['code' => 300, 'msg' => '缺少市级信息!'];

        if (!$data['province_id'])
            return ['code' => 300, 'msg' => '缺少省级信息!'];

        $goods_freight['first'] = 0;
        $goods_freight['total'] = 0;
        $goods_freight['renew'] = 0;

        //获取运费模板
        $freight = self::$model
            ->where(['id' => $data['goods_id']])
            ->field('transport_id,goods_freight')
            ->find();

        //如果没有设置运费模板  测采用设置的商品运费
        if (!$freight['transport_id']){

            $goods_freight['first'] = $freight['goods_freight'];
            $goods_freight['total'] = $freight['goods_freight'];
            $goods_freight['renew'] = 0;

        } else {


            //获取运费模板信息
            $transport_logic = D('Common/Transport', 'Logic');

            $fields = 'county_ids,city_ids,province_ids,snum,sprice,xnum,xprice,is_default';

            $transport_info = $transport_logic::$extend
                ->where(['transport_id' => $freight['transport_id']])
                ->order('is_default asc')
                ->field($fields)
                ->select();

            $default_freight = 0;


            if ($transport_info && !empty($transport_info) && is_array($transport_info)) {

                $default_renw = 0;
                $renew = 0;

                foreach ($transport_info as $v) {

                    if ((strpos($v['province_ids'], "," . $data['province_id'] . ",") !== false) &&
                        (strpos($v['county_ids'], "," . $data['county_id'] . ",") !== false) &&
                        (strpos($v['city_ids'], "," . $data['city_id'] . ",") !== false)
                    ) {

                        //计算首件每件所需要的运费

                        $eny = $v['sprice'] / $v['snum'];

                        if (intval($data['goods_num']) > $v['snum']) {

                            $goods_freight['first'] = $v['sprice'];

                        } else {

                            $goods_freight['first'] = $eny * (intval($data['goods_num']) ? intval($data['goods_num']) : 1);

                        }

                        //计算续件的运费
                        if ($data['goods_num'] && $data['goods_num'] > $v['snum']) {

                            $xuj = intval($data['goods_num']) - $v['snum'];//需要续件的数量


                            //计算续件每件的运费
                            $one_price = $v['xprice'] / $v['xnum'];

                            $renew = $one_price * intval($xuj);//计算续件运费


                        }

                    }

                    if ($v['is_default'] == 1) {


                        $eny = $v['sprice'] / $v['snum'];

                        if (intval($data['goods_num']) > $v['snum']) {

                            $default_freight = $v['sprice'];

                        } else {

                            $default_freight = $eny * (intval($data['goods_num']) ? intval($data['goods_num']) : 1);

                        }

                        if ($data['goods_num'] && $data['goods_num'] > $v['snum']) {

                            $xuj = intval($data['goods_num']) - $v['snum'];//需要续件的数量


                            //计算续件每件的运费
                            $one_price = $v['xprice'] / $v['xnum'];

                            $default_renw = $one_price * intval($xuj);//计算续件运费


                        }

                    }

                }

                $goods_freight['renew'] = $renew;

                //如果运费模板中没有指定该地区，取默认运费
                if (!$goods_freight['first'] && $default_freight) {

                    $goods_freight['first'] = $default_freight;

                    $goods_freight['renew'] = $default_renw;

                }

                $total = intval($goods_freight['renew']) + intval($goods_freight['first']);

                $goods_freight['total'] = ($total > 0) ? $total : '0' ;


            } else {

                $goods_freight['first'] = $freight['goods_freight'];
                $goods_freight['total'] = $freight['goods_freight'];
                $goods_freight['renew'] = 0;

            }

        }



        return ['code' => 200, 'data' => $goods_freight];

    }

    /**
     * @introduction: 获取商品收藏列表
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     * @param int $uid
     */

    static public function getCollectionData($uid,$page,$nums = '20')
    {

        $where = [];

        if($uid)
            $where['uid'] = $uid;


        $colletion = self::$goods_collection
                            ->where($where)
                            ->order('time desc')
                            ->page($page,$nums)
                            ->field('goods_id')
                            ->select();

        if(!$colletion)
            return ['code' => 200, 'msg' => '暂无数据!'];

        $data = [];

        foreach($colletion as $v)
        {

            $whr = "extend.is_default = 1";

            $fileds = "goods.goods_collect,goods.`like`,extend.goods_id,goods.title,goods.description,extend.goods_storage,extend.thumb,extend.goods_price,extend.goods_market_price,extend.goods_storage";

            $_data = self::$model
                        ->alias('goods')
                        ->join('__GOODS_EXTEND__ extend ON goods.id = extend.goods_id', 'LEFT')
                        ->where("goods.id = " . $v['goods_id'] . " AND $whr")
                        ->field($fileds)
                        ->find();

            if($_data)
               $data[] = $_data;

        }

        return ['code' => 200, 'data' => $data];

    }

    /**
     * @introduction: 收藏商品
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     * @param array $data 商品数据
     * @param int $uid 用户ID
     */
    static public function collection($data)
    {
        if (!$data['goods_id'])
            return ['code' => 300, 'msg' => '商品信息不能为空!'];

        //检测商品是否下架
        $order_logic = D('Common/Order','Logic');

        $res = $order_logic::checkGoodsStates($data['goods_id']);

        if(!$res)
            return ['code' => 300,'msg' => '当前商品已下架!'];


        $data['time'] = NOW_TIME;

        if (self::$goods_collection->add($data)){

            //商品收藏成功,修改商品被收藏字段加1
            self::$model->where(['id'=>$data['goods_id']])->setInc('goods_collect',1);

            return ['code' => 200, 'msg' => '收藏成功'];

        }


        return ['code' => 300, 'msg' => '收藏失败'];

    }

    /**
     * @introduction: 删除收藏
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     * @param array $data 商品数据
     * @param int $uid 用户ID
     */
    static public function delCollection($data)
    {
        if (!$data['goods_ids'])
            return ['code' => 300, 'msg' => '商品信息不能为空!'];

        $goods_ids = trim($data['goods_ids']);

        $where = "goods_id IN($goods_ids) AND uid = " . $data['uid'];

        if (self::$goods_collection->where($where)->delete()){

            //商品收藏成功,修改商品被收藏字段减一
            self::$model->where($where)->setDec('goods_collect',1);
            return ['code' => 200, 'msg' => '取消收藏成功'];

        }


        return ['code' => 300, 'msg' => '取消收藏失败'];

    }

    /**
     * @introduction: 检测商品是否被收藏
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     * @param array $data 商品数据
     * @param int $uid 用户ID
     */
    static public function checkCollection($where)
    {
        if (!$where['goods_id'])
            return ['code' => 300, 'msg' => '商品信息不能为空!'];


        if (self::$goods_collection->where($where)->count())
            return ['code' => 200];


        return ['code' => 300];

    }
    /**
     * @introduction: 更新商品状态
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     */
    static public function updateGoodsStatus($goods_id,$filed)
    {

        if(!$goods_id)
            return ['code' => 300 ,'msg' => '缺少商品ID!'];


        if(!$filed)
            return ['code' => 300 ,'msg' => '缺少商品操作类型!'];

        //return self::$model->fetchSql(true)->where(['id' => $goods_id])->setInc($filed,1);

        if(self::$model->where(['id' => $goods_id])->setInc($filed,1)){



            $data = self::$model
                ->where(['id' => $goods_id])
                ->field('views,comment,share_nums,goods_salenum,goods_collect,goods_star,like')
                ->find();


            return ['code' => 200, 'msg' => '操作成功','data' => $data];

        }

        return ['code' => 300, 'msg' => '操作失败!'];


    }

    /**
     * @introduction: 根据商品ID获取规格商品
     * @author: 杨陈鹏
     * @email: yangchenpeng@cdlinglu.com
     */
    static public function getSpecLists($goods_id,$fields = '*')
    {

        if(!$goods_id)
            return ['code' => 300, 'msg' => '缺少商品信息!'];

        $data = self::$extend
                    ->where(['goods_id' => $goods_id])
                    ->select();

        return $data;

    }
}